package cook.services;

import static cook.db.Tables.INGREDIENTS;
import static cook.db.Tables.RECIPES;

import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.jooq.CaseWhenStep;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cook.models.Ingredient;
import cook.models.Recipe;

@Service
public class CookService {
    private final static Logger logger = Logger.getLogger(CookService.class);
    @Autowired
    private DefaultDSLContext sql;

    @Autowired
    private DefaultConfiguration db;

    @Autowired
    private SolrService solrService;

    public List<String> listIngredients(int limit, final int offset) {
        if (limit < 0) {
            limit = Integer.MAX_VALUE;
        }
        return sql.select(INGREDIENTS.NAME).from(INGREDIENTS).limit(limit).offset(offset).fetch(INGREDIENTS.NAME);
    }

    public List<Recipe> recommend(final Collection<Ingredient> ingredients, int limit, final int offset)
            throws SolrServerException {
        if (limit < 0) {
            limit = 20;
        }
        final List<Integer> matches = solrService.findMLT(ingredients, limit, offset);
        
        logger.info("Docs are " + matches);
        
        CaseWhenStep<Integer, Integer> value = DSL.decode().value(RECIPES.ADM_ID).when(matches.get(0), 0);
        for (int i = 1; i < matches.size(); i++) {
            value = value.when(matches.get(i), i);
        }
        return sql.select().from(RECIPES).where(RECIPES.ADM_ID.in(matches)).orderBy(value).fetchInto(Recipe.class);
    }
}
